﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;

namespace ControlExplorer
{
  public enum WidgetType
  {
    UseCase,
    Features
  }

  public class WidgetData
  {
    private string xmlPath;

    private XElement _ele;
    private XElement Ele
    {
      get
      {
        if (_ele == null)
        {
          _ele = XElement.Load(HttpContext.Current.Server.MapPath(xmlPath));
        }
        return _ele;
      }
    }

    public WidgetData(string xmlPath)
    {
      this.xmlPath = xmlPath;
    }

    public static WidgetData FeedWidgetData(WidgetType type)
    {
      string xmlPath = string.Empty;
      switch (type)
      {
        case WidgetType.UseCase:
          xmlPath = "~/UseCaseList.xml";
          break;
        case WidgetType.Features:
          xmlPath = "~/ControlList.xml";
          break;
      }
      return new WidgetData(xmlPath);
    }


    private IEnumerable<XElement> GetAllWidgetData()
    {
      var rootwidgets = from el in Ele.Elements("Control") where el.Element("action") != null select el;
      var childWidgets = from el in Ele.Descendants("ChildControl") select el;
      return rootwidgets.Union(childWidgets).OrderBy(p => p.Attribute("name").Value);
    }

    public List<WidgetEntity> GetFavoriteWidgets()
    {
      List<WidgetEntity> widgets = new List<WidgetEntity>();
      var res = GetAllWidgetData().Where(p => p.Attribute("isFavorite") != null && p.Attribute("isFavorite").Value == "true");
      foreach (var obj in res)
      {
        widgets.Add(GetWidgetEntity(obj, true));
      }
      return widgets;
    }

    public List<WidgetEntity> GetAllWidgets()
    {
      List<WidgetEntity> widgets = new List<WidgetEntity>();
      var res = GetAllWidgetData();
      foreach (var obj in res)
      {
        widgets.Add(GetWidgetEntity(obj, false));
      }
      return widgets;
    }

    public WidgetEntity GetWidgetEntity(XElement obj, bool bigIcon)
    {
      var widget = new WidgetEntity();
      widget.WidgetName = obj.Attribute("name").Value;
      string wn = widget.WidgetName.Replace(" ", string.Empty);
      widget.WidgetHref = "~/samples/" + wn + "/Overview.aspx";
      widget.Title = obj.Attribute("text") != null ? obj.Attribute("text").Value : widget.WidgetName;
      widget.Icon = "~/explore/css/images/icons/widget/" + wn + ".png";
      if (bigIcon)
      {
        widget.Icon = "~/explore/css/images/icons/widget/" + wn + ".png";
      }
      else
      {
        widget.Icon = "~/explore/css/images/icons/widget/" + wn + ".png";
      }

      return widget;
    }
  }



	public class WidgetEntity 
	{
		public string WidgetName
		{
			get;
			set;
		}

		public string Icon
		{
			get;
			set;
		}

		public string Title
		{
			get;
			set;
		}

		public string WidgetHref
		{
			get;
			set;
		}
	}
}